//
//  XFoundViewController.m
//  Bees
//
//  Created by Xiaohan on 2018/12/13.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "XFoundViewController.h"
#import "XHomeCyclePagerCell.h"
#import "XHomeModuleCell.h"
#import "XHomeRecommendedCell.h"
#import "XHomeSegementView.h"
#import "XHomeItemContentCell.h"
#import "MJDIYHeader.h"
#import "XFoundSearchViewController.h"
#import "XInformationReviewViewController.h"
#import "XRecommendedMoreViewController.h"
#import "XRecentlyViewController.h"
#import "PCScatterViewController.h"
#import "FoundServer.h"
#import "WebInfoViewController.h"
#import "ScatterDappManager.h"
static NSString *const kTipSectionViewIdentifier = @"kTipSectionViewIdentifier";
static NSString *const kSegementViewIdentifier = @"kSegementViewIdentifier";
static NSString *const kFootMoreIdentifier = @"kFootMoreIdentifier";

@interface XFoundViewController()
@property (nonatomic,strong) FoundServer *server;
@property (nonatomic,weak) XHomeItemContentCell*contentCell;
@property (nonatomic,weak) XHomeSegementView*segementView;
@end

@implementation XFoundViewController
- (instancetype)init{
    if (self = [super init]) {
        self = [super initWithStyle:UITableViewStylePlain];
    }
    return self;
}
- (void)viewDidLoad{
    [super viewDidLoad];
    [self setupUI];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.tableView.mj_header.refreshing) {
        [self.tableView.mj_header endRefreshing];
    }
}
- (void)getData{
    [self.server getDiscoverComplete:^(BOOL success, NSString * _Nonnull msg) {
        if (success) {
            [self.tableView reloadData];
        }else{
            [self.view makeToast:msg];
        }
    }];
    if (kCurUser) {
        [self.server getCollectionListCompletion:^(BOOL success, NSString * _Nonnull msg) {
            if (success) {
                MJDIYHeader*mj_header = (MJDIYHeader*)self.tableView.mj_header;
                mj_header.collectionArr = self.server.collectionList;
            }else{
                [self.view makeToast:msg];
            }
        }];
    }
    MJDIYHeader*mj_header = (MJDIYHeader*)self.tableView.mj_header;
    mj_header.recentlyUseArr = [kUserManager getRecentlyUsed];
    self.tableView.mj_header.mj_h = kOnceOptionsHeight + (kCurUser!=nil?kOnceOptionsHeight:0);
}

#pragma mark - UI
- (void)setupUI{
    MJDIYHeader*mj_header=[MJDIYHeader headerWithRefreshingBlock:nil];
    kWeakSelf(self);
    mj_header.HeaderSectionBlock = ^(XDAPP_RecentlyType type) {
        XRecentlyViewController *vc  =[[XRecentlyViewController alloc]initWithType:type];
        [weakself.navigationController pushViewController:vc
                                                 animated:YES];
    };
    mj_header.clickItemBlock = ^(FoundRecommendModel *model) {
        [ScatterDappManager manager:weakself forDapp:model];
    };
//    kWeakSelf(mj_header);
//    mj_header.beginRefreshingCompletionBlock = ^{
//        weakmj_header.recentlyUseArr = [kUserManager getRecentlyUsed];
//    };
    self.tableView.mj_header = mj_header;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIImage *navImg = IMAGE_NAMED(@"nav_logo");
    self.navigationItem.leftBarButtonItem = nil;
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectZero];
    imageV.image = navImg;
    imageV.size = navImg.size;
    imageV.left = AdaptedWidth(8);
    imageV.centerY = titleView.centerY;
    [titleView addSubview:imageV];
    self.navigationItem.titleView = titleView;
    [self addNavigationItemWithImageNames:@[@"search"] isLeft:NO target:self action:@selector(rightBtnClick) tags:nil];
    UIView *tableBackView = [[UIView alloc] initWithFrame:CGRectMake(0, -kScreenHeight, kScreenWidth, kScreenHeight)];
    tableBackView.backgroundColor = UIColor.blackColor;
    [self.tableView addSubview:tableBackView];
    [self.tableView sendSubviewToBack:tableBackView];
    [self.tableView registerClass:XHomeTipHeadView.class forHeaderFooterViewReuseIdentifier:kTipSectionViewIdentifier];
    [self.tableView registerClass:XHomeSegementView.class forHeaderFooterViewReuseIdentifier:kSegementViewIdentifier];
}
#pragma mark - action
- (void)rightBtnClick{
    XFoundSearchViewController*vc = [[XFoundSearchViewController alloc]initWithType:FoundSearchTypeDapp];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)manageBanner:(FoundBannerModel*)banner{
    [ScatterDappManager manager:self forBanner:banner];
}
- (void)manageDappRecommend:(FoundRecommendModel*)model{
    [ScatterDappManager manager:self forDapp:model];
}

#pragma mark - table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    kWeakSelf(self);
    if (section==0) {
        XHomeCyclePagerCell*cycleCell = [XHomeCyclePagerCell cellForTableView:tableView];
        cycleCell.data = self.server.foundModel.banner;
        cycleCell.ClickBlock = ^(FoundBannerModel * _Nonnull model) {
            [weakself manageBanner:model];
        };
        return cycleCell;
    }else if (section==1){
        XHomeModuleCell*moduleCell = [XHomeModuleCell cellForTableView:tableView];
        moduleCell.data = self.server.foundModel.button;
        moduleCell.ModuleClickBlock = ^(FoundBannerModel * _Nonnull banner) {
            [weakself manageBanner:banner];
        };
        return moduleCell;
    }else if (section==2){
        XHomeRecommendedCell *recommendedCell = [XHomeRecommendedCell cellForTableView:tableView];
        recommendedCell.hasLine = YES;
        recommendedCell.data = self.server.foundModel.recommend;
        recommendedCell.ClickBlock = ^(FoundRecommendModel * _Nonnull model) {
            [weakself manageDappRecommend:model];
        };
        return recommendedCell;
    }else{
        XHomeItemContentCell *cell = [XHomeItemContentCell cellForTableView:tableView];
        self.contentCell = cell;
        cell.categoryData = self.server.foundModel.category;
        kWeakSelf(self);
        cell.MoreBtnClickBlock = ^(FoundCategoryModel* category) {
            XRecommendedMoreViewController *vc = [XRecommendedMoreViewController new];
            vc.category = category;
            [weakself.navigationController pushViewController:vc animated:YES];
        };
        cell.ItemClickBlock = ^(FoundRecommendModel * _Nonnull model) {
            [weakself manageDappRecommend:model];
        };
        cell.scrollToIndexBlock = ^(NSInteger selIndex) {
            weakself.segementView.selIndex = selIndex;
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    if (section==0) {
        return kXHomeCyclePagerHeight;
    }else if(section==1){
        return kXHomeModuleHeight;
    }else if(section==2){
        if (!self.server.foundModel.recommend.count) {
            return 0.01f;
        }
        if (self.server.foundModel.recommend.count%4==0) {
            return kHomeRecommendedHeight*(self.server.foundModel.recommend.count/4)+kHomeRecommendedTopBottomSpace;
        }else{
            return kHomeRecommendedHeight*(self.server.foundModel.recommend.count/4+1)+kHomeRecommendedTopBottomSpace;
        }
    }
    return kXHomeItemContentHeight;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        XHomeTipHeadView *recommendedTipView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kTipSectionViewIdentifier];
        recommendedTipView.titleLab.text = XLocalized(@"推荐Dapps");
        return recommendedTipView;
    }else if (section == 3){
        XHomeSegementView *segementView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kSegementViewIdentifier];
        self.segementView = segementView;
        kWeakSelf(self);
        segementView.resultBlock = ^(NSInteger index) {
            weakself.contentCell.selIndex = index;
        };
        if (![segementView.titles isEqualToArray:self.server.foundModel.categoryTitles]) {
            self.contentCell.selIndex = 0;
            self.segementView.selIndex = 0;
        }
        segementView.titles = self.server.foundModel.categoryTitles;;
        return segementView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 2 || section == 3) {
        return KHomeSegementHeight;
    }
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
//    if (section == 3) {
//        return 50.0f;
//    }
    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

#pragma mark - getter
- (FoundServer*)server{
    if (!_server) {
        _server = [FoundServer new];
    }
    return _server;
}

@end
